package com.example.fangkb;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends AppCompatActivity {
    private ImageView  likeImg;
    private Button  btnNext;
    private int[] likes ={R.drawable.like1,R.drawable.like2,
            R.drawable.like3, R.drawable.like4,R.drawable.like5,};
    private int index = 0;
    private Handler handler;
    private final int CHANGE_LIKE =1001;
    // 是否处于暂停状态
    private Boolean isPause = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        likeImg = findViewById(R.id.likeImg);
        btnNext = findViewById(R.id.btn_next);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if (message.what == CHANGE_LIKE){
                    index =(index + 1) % likes.length;
                    likeImg.setImageResource(likes[index]);
                    return true;
                }
                return false;
            }
        });


                //改用线程 自动切换
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            if (!isPause) {
                                // 在子线程中不可以修改主线程创建的View
                                // 需要使用消息机制 告诉主线程更新
                                Message message = new Message();
                                message.what = CHANGE_LIKE;
                                handler.sendMessage(message);
                                Log.e("MainActity", "send  change message");
                            }
                        }
                    }
                }).start();


                btnNext.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        isPause = !isPause;
                    }
                });
            }
        }

